/*
 *
 *   Copyright 2016 the original author or authors.
 *
 *   Licensed under the Apache License, Version 2.0 (the "License");
 *   you may not use this file except in compliance with the License.
 *   You may obtain a copy of the License at
 *
 *        http://www.apache.org/licenses/LICENSE-2.0
 *
 *   Unless required by applicable law or agreed to in writing, software
 *   distributed under the License is distributed on an "AS IS" BASIS,
 *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *   See the License for the specific language governing permissions and
 *   limitations under the License.
 *
 */

package com.shiwaixiangcun.authz.config;

import com.alibaba.druid.pool.DruidDataSourceFactory;
import com.shiwaixiangcun.core.repository.support.SimpleMybatisRepositoryFactoryBean;
import com.shiwaixiangcun.core.repository.support.SimpleMybatisRepositoryImpl;
import org.springframework.context.EnvironmentAware;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
import org.springframework.core.env.Environment;
import org.springframework.data.mybatis.repository.config.EnableMybatisRepositories;
import org.springframework.data.mybatis.support.SqlSessionFactoryBean;
import org.springframework.data.repository.query.QueryLookupStrategy;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import javax.sql.DataSource;
import java.util.Properties;

/**
 * Created by SilentWu on 2016/11/9.
 */
@Configuration
@EnableAspectJAutoProxy(proxyTargetClass = true) //启用自动代理功能。
@EnableMybatisRepositories(
        basePackages = {"com.shiwaixiangcun.authz.repository", "com.shiwaixiangcun.core.repository"},
        mapperLocations = {"classpath*:/com/shiwaixiangcun/authz/mapper/*.xml"},
        queryLookupStrategy = QueryLookupStrategy.Key.CREATE_IF_NOT_FOUND,
        repositoryImplementationPostfix = "Impl",
        repositoryBaseClass = SimpleMybatisRepositoryImpl.class,
        repositoryFactoryBeanClass = SimpleMybatisRepositoryFactoryBean.class
)
@EnableTransactionManagement
public class JPAConfig implements EnvironmentAware {

    private Environment env;

    @Bean
    public DataSource dataSource() throws Exception {
        Properties properties = new Properties();
        properties.put("url", env.getProperty("connection.url"));
        properties.put("username", env.getProperty("connection.username"));
        properties.put("password", env.getProperty("connection.password"));
        //   <!-- 配置初始化大小、最小、最大 -->
        properties.put("initialSize", env.getProperty("druid.initialSize"));
        properties.put("minIdle", env.getProperty("druid.minIdle"));
        properties.put("maxActive", env.getProperty("druid.maxActive"));
        // <!-- 配置获取连接等待超时的时间 -->
        properties.put("maxWait", env.getProperty("druid.maxWait"));
        properties.put("minIdle", env.getProperty("druid.minIdle"));
        //<!-- 配置间隔多久才进行一次检测，检测需要关闭的空闲连接，单位是毫秒 -->
        properties.put("timeBetweenEvictionRunsMillis", env.getProperty("druid.timeBetweenEvictionRunsMillis"));
        //   <!-- 配置一个连接在池中最小生存的时间，单位是毫秒 -->
        properties.put("minEvictableIdleTimeMillis", env.getProperty("druid.minEvictableIdleTimeMillis"));
        properties.put("validationQuery", env.getProperty("druid.validationQuery"));
        properties.put("testWhileIdle", env.getProperty("druid.testWhileIdle"));
        properties.put("testOnBorrow", env.getProperty("druid.testOnBorrow"));
        properties.put("testOnReturn", env.getProperty("druid.testOnReturn"));
        //<!-- 打开PSCache，并且指定每个连接上PSCache的大小  如果用Oracle，则把poolPreparedStatements配置为true，mysql可以配置为false。-->
        properties.put("poolPreparedStatements", env.getProperty("druid.poolPreparedStatements"));
        properties.put("maxPoolPreparedStatementPerConnectionSize", env.getProperty("druid.maxPoolPreparedStatementPerConnectionSize"));
        properties.put("filters", env.getProperty("druid.filters"));
        return DruidDataSourceFactory.createDataSource(properties);
    }


    @Bean
    public SqlSessionFactoryBean sqlSessionFactory(DataSource dataSource) {
        SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean();
        factoryBean.setDataSource(dataSource);
        return factoryBean;
    }

    @Bean
    public PlatformTransactionManager transactionManager(DataSource dataSource) {
        return new DataSourceTransactionManager(dataSource);
    }


    @Override
    public void setEnvironment(Environment environment) {
        this.env = environment;
    }
}
